#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
#include <unordered_map>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"

//多线程客户端，一个线程用于用户IO，一个线程用于接收广播消息

struct sockaddr_in server;  //服务器信息

static void Usage(std::string name){
    std::cout << "Usage:\n\t" << name << " server_ip server_port" << std::endl;
}


void* recv_rounite(void* arg){
    while (true)
    {
        int sockfd=*(int*)arg;
        char buff[1024];
        struct sockaddr_in client;
        socklen_t len=sizeof(client);
        ssize_t s=recvfrom(sockfd,buff,sizeof(buff),0,(struct sockaddr*)&client,&len);
        if (s > 0)
        {
            buff[s] = 0;
            std::cout << "server echo# " << buff << std::endl;
        }
        
    }
    
}
int main(int argc,char*argv[]){
    if(argc!=3){
        Usage(argv[0]);
        exit(1);
    }

    std::string server_ip=argv[1];
    uint16_t server_port=atoi(argv[2]);  

    int sockfd=socket(AF_INET,SOCK_DGRAM,0);
    assert(sockfd>0);
    
    bzero(&server,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(server_port);
    server.sin_addr.s_addr=inet_addr(server_ip.c_str());

    //接收消息
    pthread_t rev;
    pthread_create(&rev,nullptr,recv_rounite,(void*)&sockfd);
    std::string buffer;

    //用户进行IO操作
    while(true){
        std::cerr<<"please Enter#  ";
        std::getline(std::cin,buffer);
        sendto(sockfd,buffer.c_str(),buffer.size(),0,(const struct sockaddr*)&server,sizeof(server));
    }
    close(sockfd);

    return 0;
}